<script setup>
import executeTransform from './utils/DocUtil'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const nameVal = ref('')
const typeVal = ref('')
const descVal = ref('')
const isSuccess = ref(false)
const handleTransform = async () => {
  if (!typeVal.value) return
  try {
    await executeTransform(typeVal, nameVal, descVal)
    isSuccess.value = true
    setTimeout(() => {
      isSuccess.value = false
    }, 1500)
  } catch (error) {
    window.alert(error)
  }
}

const handleClear = () => {
  nameVal.value = ''
  descVal.value = ''
  typeVal.value = ''
}

const getCopyText = async () => {
  const permits = await navigator.permissions.query({ name: 'clipboard-read' })
  const hasFocus = document.hasFocus() //这个是重点，可判断是否为当前dom页面
  if (hasFocus && (permits.state === 'granted' || permits.state === 'prompt')) {
    return await navigator.clipboard.readText()
  }
}
const getHiddenStatus = async () => {
  try {
    const isHidden = document.hidden
    if (isHidden) return
    typeVal.value = await getCopyText()
  } catch (error) {
    console.error(error)
  }
}

const handleAddListener = () => {
  document.addEventListener('visibilitychange', getHiddenStatus, true)
}

onMounted(() => handleAddListener())
</script>

<template>
  <div class="u-flex u-justify-center">
    <div>
      <div class="row level">
        <div class="tag tag--info">名称</div>
        <input class="mt-1" v-model="nameVal" placeholder="在这里输入名称" />
      </div>
      <div class="row level">
        <div class="tag tag--info">描述</div>
        <input class="mt-1" v-model="descVal" placeholder="在这里输入描述" />
      </div>
      <button
        class="mt-1 btn-info"
        :class="{ 'btn-success btn--disabled': isSuccess }"
        @click="handleTransform">
        {{ isSuccess ? 'success' : 'transform' }}
      </button>
      <button class="mt-1 ml-1 btn-danger" @click="handleClear">clear</button>
    </div>
    <div class="ml-10">
      <div class="tag tag--primary">类型</div>
      <textarea
        class="textarea mt-1"
        v-model="typeVal"
        placeholder="在这里输入类型" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
#app {
  height: 100vh;
}
.textarea {
  min-width: 50vh;
  min-height: 70vh;
}
</style>
